#!/bin/bash

# 创建 WeKnora 部署包脚本
# 将所有需要上传到服务器的文件打包成一个压缩文件

set -e # 遇到错误时退出

# 设置颜色
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # 无颜色

# 日志函数
log_info() {
    printf "%b\n" "${BLUE}[INFO]${NC} $1"
}

log_warning() {
    printf "%b\n" "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    printf "%b\n" "${RED}[ERROR]${NC} $1"
}

log_success() {
    printf "%b\n" "${GREEN}[SUCCESS]${NC} $1"
}

# 检查必要文件是否存在
check_files() {
    log_info "检查必要文件..."
    
    if [ ! -d "weknora-deployment" ]; then
        log_error "weknora-deployment 目录不存在"
        exit 1
    fi
    
    local required_files=(
        "weknora-deployment/docker-compose-prod.yml"
        "weknora-deployment/.env.prod"
        "weknora-deployment/simple-deploy.sh"
        "weknora-deployment/load-images.sh"
        "weknora-deployment/DEPLOYMENT_INSTRUCTIONS.md"
        "weknora-deployment/DEPLOYMENT_README.md"
        "weknora-deployment/deploy-with-stack.sh"
        "weknora-deployment/fix-swarm-deployment.sh"
    )
    
    local missing_files=()
    for file in "${required_files[@]}"; do
        if [ ! -f "$file" ]; then
            log_error "缺少文件: $file"
            missing_files+=("$file")
        fi
    done
    
    if [ ${#missing_files[@]} -gt 0 ]; then
        log_error "缺少 ${#missing_files[@]} 个文件，无法创建部署包"
        exit 1
    fi
    
    log_success "所有必要文件检查通过"
}

# 创建部署包
create_package() {
    log_info "创建部署包..."
    
    local package_name="weknora-deployment-$(date +%Y%m%d_%H%M%S).tar.gz"
    
    # 创建压缩包
    tar -czf "$package_name" weknora-deployment
    
    log_success "部署包已创建: $package_name"
    
    # 显示压缩包信息
    log_info "压缩包信息:"
    ls -lh "$package_name"
    
    log_success "部署包创建完成！"
    log_info "请将 $package_name 传输到服务器并解压使用"
}

# 显示使用帮助
show_help() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo " -h, --help     显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0            # 创建部署包"
}

# 解析命令行参数
if [ $# -gt 0 ]; then
    case $1 in
        -h | --help )       show_help
                            exit 0
                            ;;
        * )                 log_error "未知选项: $1"
                            show_help
                            exit 1
                            ;;
    esac
fi

# 执行创建包
main() {
    log_info "开始创建 WeKnora 部署包"
    
    check_files
    create_package
    
    log_success "部署包创建完成！"
    log_info "请将生成的压缩包传输到服务器并解压使用"
}

main "$@"
